package com.huilian.iotbox.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huilian.iotbox.admin.dao.DeviceBuyOrderDao;
import com.huilian.iotbox.admin.service.*;
import com.huilian.iotbox.admin.websocket.WebSocket;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.config.AgencyConfig;
import com.huilian.iotbox.data.config.MiddlewareConfig;
import com.huilian.iotbox.data.dto.DeviceBuyOrderDto;
import com.huilian.iotbox.data.dto.DevicePriceDto;
import com.huilian.iotbox.data.enums.*;
import com.huilian.iotbox.data.exception.ControllerException;
import com.huilian.iotbox.data.po.DeviceBuyOrder;
import com.huilian.iotbox.data.po.SystemMerchantConfig;
import com.huilian.iotbox.data.po.User;
import com.huilian.iotbox.data.properties.ConfigProperties;
import com.huilian.iotbox.data.service.SystemMerchantConfigSerivce;
import com.huilian.iotbox.data.utils.HttpUtils;
import com.huilian.iotbox.data.utils.HttpsMain;
import com.huilian.iotbox.data.utils.SciCalUtils;
import com.huilian.iotbox.data.vo.DeviceBuyOrderVo;
import com.huilian.iotbox.data.vo.DevicePayeeAccountVo;
import com.huilian.iotbox.data.vo.DevicePriceVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 谢洛涛
 * @date 2021/9/7 16:26
 */
@Slf4j
@Service
public class DeviceBuyOrderServiceImpl implements DeviceBuyOrderService {
    @Resource
    private DeviceBuyOrderDao deviceBuyOrderDao;
    @Autowired
    private UserService userService;
    @Resource
    private WebSocket webSocket;
    @Autowired
    private WXMessageService wxMessageService;
    private static String notifyUrl = "http://iotbox.huilian.cloud/admin/api/deviceBuyOrder/notice";

    @Override
    public String payQrCodeNotify(HttpServletRequest request) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String tempLine = "";
        StringBuffer resultBuffer = new StringBuffer();
        while ((tempLine = reader.readLine()) != null) {
            resultBuffer.append(tempLine).append(System.getProperty("line.separator"));
        }
        String response = resultBuffer.toString();

        final Map<String, Object> res = HttpUtils.getResultData(response);
        Map<String, String> result = (Map<String, String>) res.get("data");
        String outTradeNo = result.get("outTradeNo");
        String channelType = result.get("channelType");
        String totalAmount = result.get("totalAmount");
        if (StringUtils.isEmpty(outTradeNo) || StringUtils.isEmpty(totalAmount)) {
            throw new ControllerException("返回参数有误!");
        }
        BigDecimal amount = new BigDecimal(totalAmount).divide(new BigDecimal("100"));
        amount = SciCalUtils.sciCalToBD(amount.doubleValue(), 2);
        // 查看设备购买订单表
        DeviceBuyOrderVo deviceBuyOrderVo = deviceBuyOrderDao.findDeviceBuyOrderByOutTradeNoAndTotalAmount(outTradeNo, amount);
        if (deviceBuyOrderVo == null) {
            throw new ControllerException("订单信息有误!");
        }
        if (DeviceBuyOrderStatusEnum.WIAT_DELIVER.getCode().equals(deviceBuyOrderVo.getStatus())) {
            log.info("购买设备:" + deviceBuyOrderVo.getOutTradeNo() + "已完成");
            return "SUCCESS";
        }
        if ("ALI".equals(channelType)) {
            channelType = "01";
        } else {
            channelType = "02";
        }
        DeviceBuyOrder deviceBuyOrder = new DeviceBuyOrder();
        deviceBuyOrder.setOrderNo(result.get("orderNo"));
        deviceBuyOrder.setMerchantOrderNo(result.get("merchantOrderNo"));
        deviceBuyOrder.setId(deviceBuyOrderVo.getId());
        deviceBuyOrder.setChannelType(channelType);
        deviceBuyOrder.setStatus(DeviceBuyOrderStatusEnum.WIAT_DELIVER.getCode());
        deviceBuyOrderDao.update(deviceBuyOrder);

        String key = "deviceBuy-" + deviceBuyOrderVo.getUserId() + "-" + deviceBuyOrderVo.getMobile();
        webSocket.qrCodePayNotify("SUCCESS", key);
        return "SUCCESS";
    }

    @Override
    public String largeTransferNotice(HttpServletRequest request) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String tempLine = "";
        StringBuffer resultBuffer = new StringBuffer();
        while ((tempLine = reader.readLine()) != null) {
            resultBuffer.append(tempLine).append(System.getProperty("line.separator"));
        }
        String response = resultBuffer.toString();
        log.info("大额转账通知报文{}", response);
        final Map<String, Object> res = HttpUtils.getResultData(response);
        Map<String, String> result = (Map<String, String>) res.get("data");
        String outTradeNo = result.get("outTradeNo");
        String totalAmount = result.get("totalAmount");
        String status = result.get("status");
        if (StringUtils.isEmpty(outTradeNo) || StringUtils.isEmpty(totalAmount)) {
            throw new ControllerException("返回参数有误!");
        }
        BigDecimal amount = new BigDecimal(totalAmount).divide(new BigDecimal("100"));
        amount = SciCalUtils.sciCalToBD(amount.doubleValue(), 2);
        //根据单号、金额 查询订单
        DeviceBuyOrderVo deviceBuyOrderVo = deviceBuyOrderDao.findDeviceBuyOrderByOutTradeNoAndTotalAmount(outTradeNo, amount);
        if ("SUCCESS".equals(status)) {
            if (deviceBuyOrderVo == null) {
                throw new ControllerException("订单信息有误!");
            }
            if (DeviceBuyOrderStatusEnum.WIAT_DELIVER.getCode().equals(deviceBuyOrderVo.getStatus())) {
                log.info("购买设备:" + deviceBuyOrderVo.getOutTradeNo() + "已完成");
                return "SUCCESS";
            }
            DeviceBuyOrder deviceBuyOrder = new DeviceBuyOrder();
            deviceBuyOrder.setId(deviceBuyOrderVo.getId());
            deviceBuyOrder.setPaymentCardNo(result.get("payerCardNo"));
            deviceBuyOrder.setPaymentCertName(result.get("payerCardName"));
            deviceBuyOrder.setStatus(DeviceBuyOrderStatusEnum.WIAT_DELIVER.getCode());
            User user = userService.findUserById(deviceBuyOrderVo.getPayeeUserId());
            if (!StringUtils.isEmpty(user)) {
                if (user.getOpenId() != null) {
                    wxMessageService.sendPayMessage(deviceBuyOrderVo, user.getOpenId());
                }
            }
            deviceBuyOrderDao.update(deviceBuyOrder);
            String key = "deviceBuy-" + deviceBuyOrderVo.getUserId() + "-" + deviceBuyOrderVo.getMobile();
            webSocket.qrCodePayNotify("SUCCESS", key);
            return "SUCCESS";
        } else {
            DeviceBuyOrder deviceBuyOrder = new DeviceBuyOrder();
            deviceBuyOrder.setId(deviceBuyOrderVo.getId());
            deviceBuyOrder.setStatus(DeviceBuyOrderStatusEnum.FAIL.getCode());
//            deviceBuyOrder.setFailReason();
            deviceBuyOrderDao.update(deviceBuyOrder);
            return "FAIL";
        }
    }

}
